package com.itheima.sentinel;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import com.alibaba.fastjson.JSONObject;
import com.itheima.utils.ResultUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("user")
public class SentinelController {


    @RequestMapping(value = "/findById")
    @SentinelResource(value = "findById",
            blockHandlerClass = CommonBlockHandler.class,
            blockHandler = "handlerException2")
    public JSONObject findById(Integer id){
        return ResultUtils.successData("list", "成功！");
    }


    @PostConstruct
    public static void initFlowRules(){
        List<FlowRule> rules = new ArrayList<>();
        FlowRule flowRule = new FlowRule();

        // 设置受保护的资源
        flowRule.setResource("findById");

        // 流控规则 QPS
        flowRule.setGrade(RuleConstant.FLOW_GRADE_QPS);

        // 设置受保护的资源阈值
        flowRule.setCount(1);

        rules.add(flowRule);
        FlowRuleManager.loadRules(rules);
    }
}
